package com.cskaoyan.wx.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.CouponUserMapper;
import com.cskaoyan.mapper.FeedbackMapper;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.utils.UserUtils;
import com.cskaoyan.wx.bo.CouponCodeBO;
import com.cskaoyan.wx.bo.CouponIdBO;
import com.cskaoyan.wx.bo.WxCouponBO;
import com.cskaoyan.wx.bo.WxFeedBackBO;
import com.cskaoyan.wx.vo.WxCouponVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service


public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    FeedbackMapper feedbackMapper;

    /**
     * 优惠券列表
     *
     * @param wxCouponBO
     * @return
     */
    @Override
    public WxCouponVO getCouponList(WxCouponBO wxCouponBO) {
        PageHelper.startPage(wxCouponBO.getPage(), wxCouponBO.getSize());
        CouponExample couponExample = new CouponExample();
        couponExample.setOrderByClause("end_time");
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        criteria.andTypeEqualTo((short) 0);
        criteria.andStatusEqualTo((short) 0);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        PageInfo<Coupon> couponPageInfo = new PageInfo<>(coupons);
        long total = couponPageInfo.getTotal();
        WxCouponVO wxCouponVO = new WxCouponVO();
        wxCouponVO.setCount(total);
        wxCouponVO.setData(coupons);
        return wxCouponVO;
    }

    /**
     * 我的优惠券
     *
     * @param wxCouponBO
     * @return
     */
    @Override
    public WxCouponVO getCouponMyList(WxCouponBO wxCouponBO) {
        PageHelper.startPage(wxCouponBO.getPage(), wxCouponBO.getSize());

        Integer id = UserUtils.getUserId();

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria1 = couponUserExample.createCriteria();
        criteria1.andDeletedNotEqualTo(true);
        criteria1.andStatusEqualTo(wxCouponBO.getStatus());
        criteria1.andUserIdEqualTo(id);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        List<Coupon> coupons = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            Integer couponId = couponUser.getCouponId();
            CouponExample couponExample = new CouponExample();
            couponExample.setOrderByClause("end_time");
            CouponExample.Criteria criteria = couponExample.createCriteria();
            criteria.andDeletedNotEqualTo(true);
            criteria.andIdEqualTo(couponId);
            List<Coupon> coupons1 = couponMapper.selectByExample(couponExample);
            for (Coupon coupon : coupons1) {
                coupons.add(coupon);
            }
        }

        PageInfo<Coupon> couponPageInfo = new PageInfo<>(coupons);
        long total = couponPageInfo.getTotal();

        WxCouponVO wxCouponVO = new WxCouponVO();
        wxCouponVO.setCount(total);
        wxCouponVO.setData(coupons);
        return wxCouponVO;
    }

    /**
     * 领取优惠券
     *
     * @param couponId
     * @param session
     * @return
     */
    @Override
    public int receiveCoupon(CouponIdBO couponId) {
        Integer id = UserUtils.getUserId();

        //查看用户是否有该优惠券
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        criteria.andUserIdEqualTo(id);
        criteria.andCouponIdEqualTo(couponId.getCouponId());
        //已有该优惠券的数量
        long l = couponUserMapper.countByExample(couponUserExample);

        Coupon coupon = couponMapper.selectByPrimaryKey(couponId.getCouponId());
        //如果没有该优惠券
        if (l == 0) {
            //更新优惠券数量
            coupon.setUpdateTime(new Date());
            if (coupon.getTotal() > 0) {//原始数量大于0
                coupon.setTotal(coupon.getTotal() - 1);
                couponMapper.updateByPrimaryKeySelective(coupon);
                //获得更新后的优惠券
                Coupon coupon1 = couponMapper.selectByPrimaryKey(coupon.getId());
                //更新后的数量=0
                if (coupon1.getTotal() == 0){
                    //下架
                    coupon1.setStatus((short) 2);
                    couponMapper.updateByPrimaryKeySelective(coupon1);
                    return 3;
                }
                addMyCoupon(id, coupon, couponId.getCouponId());
                return 0;
            }else {//原始数量等于0，无限制
                couponMapper.updateByPrimaryKeySelective(coupon);

                addMyCoupon(id, coupon, couponId.getCouponId());
                return 0;
            }
            //加入我的优惠券

            //如果有
        } else if (l > 0 &&  coupon.getStatus() == 0) {
            //更新优惠券数量
            coupon.setUpdateTime(new Date());
            if (coupon.getTotal() > 0) {//原始数量大于0
                coupon.setTotal(coupon.getTotal() - 1);
                couponMapper.updateByPrimaryKeySelective(coupon);
                //获得更新后的优惠券
                Coupon coupon1 = couponMapper.selectByPrimaryKey(coupon.getId());

                //原始limit=1限领一张
                if (coupon.getLimit() == 1){
                    return 2;
                }else {
                    //limit=0无限领
                    //加入我的优惠券
                    addMyCoupon(id, coupon, couponId.getCouponId());
                    //更新后的数量=0时
                    if (coupon1.getTotal() == 0){
                        //下架
                        coupon1.setStatus((short) 2);
                        couponMapper.updateByPrimaryKeySelective(coupon1);
                        return 3;
                    }
                    return 0;
                }
            }else{//原始数量等于0，无限制
                couponMapper.updateByPrimaryKeySelective(coupon);
                //原始limit=1限领一张
                if (coupon.getLimit() == 1){
                    return 2;
                }else {
                    //limit=0无限领
                    //加入我的优惠券
                    addMyCoupon(id, coupon, couponId.getCouponId());
                    return 0;
                }
            }

        } else {
            //如果不能再领取
            return 3;
        }

    }

    /**
     * 加入我的优惠券
     * @param id
     * @param coupon
     * @param couponId2
     */
    private void addMyCoupon(Integer id, Coupon coupon, int couponId2) {
        CouponUser couponUser = new CouponUser();
        couponUser.setId(null);
        couponUser.setUserId(id);
        couponUser.setCouponId(couponId2);
        couponUser.setStatus(coupon.getStatus());
        couponUser.setUsedTime(null);
        couponUser.setStartTime(coupon.getStartTime());
        couponUser.setEndTime(coupon.getEndTime());
        couponUser.setOrderId(null);
        Date date = new Date();
        couponUser.setAddTime(date);
        couponUser.setUpdateTime(null);
        couponUser.setDeleted(false);
        couponUserMapper.insertSelective(couponUser);
    }

    /**
     * 兑换码兑换优惠券
     *
     * @param code
     * @param session
     * @return
     */
    @Override
    public int exchangeCoupon(CouponCodeBO code) {
        Integer id = UserUtils.getUserId();

        //判断优惠券是否存在
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        criteria.andTypeEqualTo((short) 2);
        criteria.andStatusEqualTo((short) 0);
        criteria.andCodeEqualTo(code.getCode());
        long l = couponMapper.countByExample(couponExample);
        if (l == 0) {
            return 1;
        }
        Coupon coupon = couponMapper.selectCouponByCode(code.getCode());

        //存在判断用户是否拥有
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria1 = couponUserExample.createCriteria();
        criteria1.andDeletedNotEqualTo(true);
        criteria1.andUserIdEqualTo(id);
        criteria1.andCouponIdEqualTo(coupon.getId());
        long size = couponUserMapper.countByExample(couponUserExample);

        //没有
        if (size == 0) {
            //更新优惠券数量
            coupon.setUpdateTime(new Date());
            if (coupon.getTotal() > 0) {//原始数量大于0
                coupon.setTotal(coupon.getTotal() - 1);
                couponMapper.updateByPrimaryKeySelective(coupon);
                //获得更新后的优惠券
                Coupon coupon1 = couponMapper.selectByPrimaryKey(coupon.getId());
                //更新后的数量=0
                if (coupon1.getTotal() == 0){
                    //下架
                    coupon1.setStatus((short) 2);
                    couponMapper.updateByPrimaryKeySelective(coupon1);
                    return 3;
                }
                addMyCoupon(id, coupon, coupon.getId());
                return 0;
            }else if (coupon.getTotal() == 0){//原始数量等于0，无限制
                couponMapper.updateByPrimaryKeySelective(coupon);
                addMyCoupon(id, coupon, coupon.getId());
                return 0;
            }

        } else if (size > 0 && coupon.getStatus()==0) {
            //更新优惠券数量
            coupon.setUpdateTime(new Date());
            if (coupon.getTotal() > 0) {//原始数量大于0
                coupon.setTotal(coupon.getTotal() - 1);
                couponMapper.updateByPrimaryKeySelective(coupon);
                //获得更新后的优惠券
                Coupon coupon1 = couponMapper.selectByPrimaryKey(coupon.getId());

                //原始limit=1限领一张
                if (coupon.getLimit() == 1){
                    return 2;
                }else {
                    //limit=0无限领
                    addMyCoupon(id, coupon, coupon.getId());
                    //更新后的数量=0
                    if (coupon1.getTotal() == 0){
                        //下架
                        coupon1.setStatus((short) 2);
                        couponMapper.updateByPrimaryKeySelective(coupon1);
                        return 3;
                    }
                    return 0;
                }
            }else if (coupon.getTotal() == 0){//原始数量等于0，无限制
                couponMapper.updateByPrimaryKeySelective(coupon);
                //原始limit=1限领一张
                if (coupon.getLimit() == 1){
                    return 2;
                }else {
                    //limit=0无限领
                    addMyCoupon(id, coupon, coupon.getId());

                    return 0;
                }
            }
        }
        return 3;
    }

    /**
     * 发送意见反馈
     *
     * @param wxFeedBackBO
     * @param session
     */
    @Override
    public void submitFeedBack(WxFeedBackBO wxFeedBackBO) {
        Integer id = UserUtils.getUserId();
        String username = userMapper.getUsernameById(id);

        Feedback feedback = new Feedback();
        feedback.setId(null);
        feedback.setUserId(id);
        feedback.setUsername(username);
        feedback.setMobile(wxFeedBackBO.getMobile());
        feedback.setFeedType(wxFeedBackBO.getFeedType());
        feedback.setContent(wxFeedBackBO.getContent());
        feedback.setStatus(0);
        feedback.setHasPicture(wxFeedBackBO.isHasPicture());
        feedback.setPicUrls(wxFeedBackBO.getPicUrls());
        feedback.setAddTime(new Date());
        feedback.setUpdateTime(null);
        feedback.setDeleted(false);

        feedbackMapper.insert(feedback);
    }

    /**
     * 我的可用优惠券
     *
     * @param session
     * @return
     */
    @Override
    public List<Coupon> selectMyCoupon() {
        Integer id = UserUtils.getUserId();

        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria1 = couponUserExample.createCriteria();
        criteria1.andDeletedNotEqualTo(true);
        criteria1.andStatusEqualTo((short) 0);
        criteria1.andUserIdEqualTo(id);
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        List<Coupon> coupons = new ArrayList<>();
        for (CouponUser couponUser : couponUsers) {
            Integer couponId = couponUser.getCouponId();
            CouponExample couponExample = new CouponExample();
            couponExample.setOrderByClause("end_time");
            CouponExample.Criteria criteria = couponExample.createCriteria();
            criteria.andDeletedNotEqualTo(true);
            criteria.andIdEqualTo(couponId);
            criteria.andStatusEqualTo((short) 0);
            criteria.andTypeEqualTo((short) 0);
            List<Coupon> coupons1 = couponMapper.selectByExample(couponExample);
            for (Coupon coupon : coupons1) {
                coupons.add(coupon);
            }
        }

        return coupons;
    }

}
